package com.example.tuter.webview;

import static com.example.tuter.util.CookieUtil.parseCookieToMap;
import static com.example.tuter.util.CookieUtil.syncUserCookie;

import android.app.Activity;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;

import java.util.Map;

public class MyWebViewClient extends WebViewClient {


    Activity activity;

    public MyWebViewClient(Activity activity) {
        this.activity = activity;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }


    @Override
    public void onPageFinished(WebView view, String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptThirdPartyCookies(view, true);
        String cookieStr = cookieManager.getCookie(url);
        Map<String, String> cookieMap;
        if (!"".equals(cookieStr)) {
            cookieMap = parseCookieToMap(cookieStr);
            //更新用户cookie
            syncUserCookie(cookieMap);
        }
        super.onPageFinished(view, url);
    }


    @Nullable
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return super.shouldInterceptRequest(view, request);
    }
}
